package com.x.erp.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

public class ExcelUtils {
	private static XSSFCellStyle cellStyle = null;

	public static Workbook initTitle(String sheetName, String[] titles) throws IOException {
		Workbook webBook = new XSSFWorkbook();
		Sheet sheet = webBook.createSheet(sheetName);
		int rows = 0;
		Row row = sheet.createRow(rows++);
		int titleCellNum = 0;
		for(String title:titles) {
			Cell cell = row.createCell(titleCellNum++);
			cell.setCellValue(title);
		}
		return webBook;
	}

	public static void writeExcel(HttpServletResponse response, Workbook work, String fileName) throws IOException {
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType("application/ms-excel;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName + ".xlsx", "UTF-8"))));
			work.write(out);
		} catch (IOException e) {
			System.out.println("输出流错误");
			e.printStackTrace();
		} finally {
			out.close();
		}
	}

	private static Cell setCellStyleWithStyleAndValue(CellStyle style, Cell cell, String value) {
		cell.setCellStyle(style);
		cell.setCellValue(value);
		return cell;
	}

	private static Cell setCellStyleWithValue(Cell cell, String value) {
		cell.setCellStyle(cellStyle);
		cell.setCellValue(value);
		return cell;
	}


	private static Cell setCellStyleWithStyleAndValue(CellStyle style, Cell cell, RichTextString value) {
		cell.setCellStyle(style);
		cell.setCellValue(value);
		return cell;
	}

	private static Cell setCellStyleWithValue(Cell cell, int value) {
		cell.setCellStyle(cellStyle);
		cell.setCellValue(value);
		return cell;
	}

	private static Cell setCellStyleWithValue(Cell cell, double value) {
		cell.setCellStyle(cellStyle);
		cell.setCellValue(value);
		return cell;
	}

}
